#!/bin/bash -l

# /tmp/.X11-unix/
# /tmp/.X1-lock

action=$1


# 因为父进程中调用指令的关系，下面这一行信息不会输入
echo "|APP_STDIO_NAME in startx: ${APP_STDIO_NAME}|"
exec 1>$APP_STDIO_NAME; exec 2>$APP_STDIO_NAME

DEBUG_XLORIE=0

if [ "$action" == "" ]; then
	action=normal_start
fi

function init_uimode() {
	echo "\${DirGuiConf}: ${DirGuiConf}" >>/tmp/test.txt

	curruser=`whoami`
	needinit=0
	if [ ! -d ${DirGuiConf} ]; then
		needinit=1
	fi
	if [ ! -f ${PATHUIMODE} ]; then
		needinit=1
	fi
	if [ ! -f ${PATH_VMDPI} ]; then
		needinit=1
	fi

	if [ $needinit -eq 0 ]; then
		echo "当前用户(${curruser})的 uimode 已初始化过"
		return
	else
		echo "当前用户(${curruser})的 uimode 正在初始化"
	fi

	rm -rf ${DirBakConf}
	mkdir -p ${DirGuiConf} 2>/dev/null
	cp -rf ${tools_dir}/misc/def_xconf/. ${DirBakConf}
	if [ $? -ne 0 ]; then
		echo "def_xconf 复制失败！";
	fi

	# default uimode
	${tools_dir}/vm_setuimode.sh phone

	# ls -al ~/.droidvm/

	rm -rf ~/.jwmrc
	ln -sf ~/.droidvm/.jwmrc ~/.jwmrc

	# mimetype 关联启动
	mkdir -p ~/.config 2>/dev/null
	cp -rf ${DirBakConf}/common/mimeapps.list  ~/.config/mimeapps.list

	# 右键菜单
	mkdir -p ~/.local/share/file-manager/actions 2>/dev/null
	cp -rf ${DirBakConf}/common/.local/share/file-manager/actions/*  ~/.local/share/file-manager/actions/

	chmod 755 ${tools_dir}/zzswmgr/zzswmgr.py
}

function run_once() {
	#Start DBUS session bus for trash/回收站
	# grep show_trash=1 ~/.config/pcmanfm/default/desktop-items-0.conf
	# if [ $? -eq 0 ]; then
	if [ -f ${app_home}/app_boot_config/trash_enable ]; then
		echo "正在启动回收站相关进程"
		if [ -z "$DBUS_SESSION_BUS_ADDRESS" ]; then
			eval $(dbus-launch --sh-syntax --exit-with-session)
		fi
		/usr/libexec/gvfsd &
	fi

	# 加上或去掉都基本没影响
	# /usr/libexec/at-spi-bus-launcher &
	# /usr/libexec/at-spi2-registryd --use-gnome-session &
}

function resize_screen() {
	tmp_fbw=$1
	tmp_fbh=$2

	echo "screent resizing to ${tmp_fbw} ${tmp_fbh}"

	# set -x	# echo on
	# ## 用这种方式切换分辨率，会导致 DisplayWidth() 取到的值 和 从屏幕文件中取到的 fb_width 不一致！
	# # xrandr --fb ${tmp_fbw}x${tmp_fbh}

	xrandr
	mode_name=${tmp_fbw}x${tmp_fbh}
	xrandr --newmode "${mode_name}" \
	109.00 \
	${tmp_fbw} ${tmp_fbw} ${tmp_fbw} ${tmp_fbw}  \
	${tmp_fbh} ${tmp_fbh} ${tmp_fbh} ${tmp_fbh} \
	-hsync +vsync

	if [ "${XSRV_NAME}" == "Xvfb" ] || [ "${XSRV_NAME}" == "xlorie" ]; then
		xrandr --addmode screen "${mode_name}"
	fi
	if [ "${XSRV_NAME}" == "Xtigervnc" ]; then
		xrandr --addmode VNC-0 "${mode_name}"
	fi
	xrandr -s ${mode_name}
	xrandr

	# set +x	# echo off
}

function xconfig() {
	# 实测在proot环境中无效的配置项
	# Xcursor.size: 64
	# gxmessage*faceSize: 80

	cat <<- EOF > ~/.Xresources

		Xft.dpi: ${VM_DPI}
		Xcursor.size: 64

		xterm*locale: zh_CN.UTF-8
		xterm*faceName: Monospace
		xterm*faceSize: 14
		xterm*scrollBar: true
		xterm*rightScrollBar: true

		gxmessage*locale: zh_CN.UTF-8
		gxmessage*faceName: Monospace
		gxmessage*faceSize: 30

	EOF

	xrdb -merge ~/.Xresources
}

function propt_webCtrl_msg() {

	# 固定端口!
	server_port=8000

	cat <<- EOF > /tmp/msg.txt

	通过浏览器控制此模拟器
	================================
	请在同一wifi下的电脑或手机上用网页浏览器访问以下地址:

	EOF

	/exbin/tools/vm_ip2link.sh "http://" ":${server_port}">>/tmp/msg.txt

	cat <<- EOF >> /tmp/msg.txt

	关闭这个窗口不影响功能.

	EOF

	gxmessage -title "web远程控制" -file /tmp/msg.txt -center
}

function rm_app_buildin_roms() {
	for i in `ls -A ${app_home}/roms 2>/dev/null`; do
		rm -rf ${app_home}/roms/$i
		touch  ${app_home}/roms/$i
	done
}

function create_quick_up_script() {
	cat <<- EOF >> ${app_home}/xlorie_quickup.sh

		source \${app_home}/xlorie_quickup.rc

		echo2apk '#vmSwitch2DesktopMode'

		rm -rf /tmp/.X11-unix/*
		rm -rf /tmp/.X*-lock

		echo "正在启动xserver-xlorie"
		echo "#startlorie ${DISPLAY} ${VM_DPI}">\$NOTIFY_PIPE
	EOF
	chmod a+x ${app_home}/xlorie_quickup.sh


	cat <<- EOF >> ${app_home}/xlorie_quickup.rc
		export XSRV_NAME=${XSRV_NAME}
		export DISPLAY=${DISPLAY}
		export MAX_FRAMEBUFFER_WIDTH=4096
		export MAX_FRAMEBUFFER_HEIGHT=4096
		export VM_DPI=\`cat \${PATH_VMDPI}1\`
	EOF
	chmod a+x ${app_home}/xlorie_quickup.rc
}

function rm_flag_files() {


	if [ -f ${APP_FILENAME_URLTOOLS} ]; then
		# if [ "1.32" == "${APP_RELEASE_VERSION}" ]; then
		if [ 1 -eq 0 ]; then
			# 测试时不删除
			:
		else
			rm -rf ${APP_FILENAME_URLTOOLS}
		fi
	fi

	if [ -f /tmp/firsttime_bootmsg.txt ]; then
		gxmessage -title "欢迎使用虚拟电脑" -file /tmp/firsttime_bootmsg.txt  -center
		rm -rf /tmp/firsttime_bootmsg.txt
	fi

	if [ -f /tmp/osbackupmsg.txt ]; then
		gxmessage -title "系统备份信息" -file /tmp/osbackupmsg.txt  -center -buttons "打开目录:0,我知道了:1"
        case "$?" in
            "0")
                open ${tools_dir}/imgbak/
                ;;
            *) 
				:
                ;;
        esac
		rm -rf /tmp/osbackupmsg.txt
	fi

	if [ -f /tmp/osrestoremsg.txt ]; then
		gxmessage -title "系统还原信息" -file /tmp/osrestoremsg.txt  -center
		rm -rf /tmp/osrestoremsg.txt
	fi



	rm_app_buildin_roms

	if [ "${ENABLE_WEB_CONTROL}" != "" ]; then propt_webCtrl_msg; fi

	ps ax|grep gxmessage|grep "VNC远程控制"
	TMP_RETURN_CODE=$?
	if [ "${vncPort}" != "" ] && [ $TMP_RETURN_CODE -ne 0 ] ; then
		gxmessage -title "VNC远程控制"     $'\nVNC服务端正在运行，端口号：'${vncPort}$'\n请确认是否是您本人启动的。\n\n如需停止，请依次点击：\n　开始使用->远程控制->通过webvnc->停止VNC\n\n如需调分辨率，请依次点击：\n　开始使用->远程控制->通过webvnc->调整分辨率\n\n如需修改密码，请依次点击：\n　开始使用->远程控制->通过webvnc->修改密码\n\n如需调小图标，请随便打开一个文件夹窗口，然后同时按 CTRL和减号\n\n'  -center
	fi

	# dist_codename=`lsb_release -c 2>/dev/null|grep name| cut -b 11-`
	# if [ "${LINUX_DISTRIBUTION}" != "debian" ] || [ "${dist_codename}" != "trixie" ]; then
	# 	echo -e "\n\napp当前版本是${APP_RELEASE_VERSION}, 从1.51版开始, app专门适配的虚拟系统调整为debain-13, 且软件管家不再支持ubuntu. \n\n看到这个提示说明您可能是从旧版升级过来的, 建议您清掉app数据, 然后重装安装虚拟系统。\n\n" > "/exbin/tmp/promptmsg.txt"
	# 	echo2apk "#promptmsg"
	# fi

	ps ax|grep gxmessage|grep "提速"
	TMP_RETURN_CODE=$?
	if [ "${XSRV_NAME}" == "Xvfb" ] && [ $TMP_RETURN_CODE -ne 0 ] ; then
		gxmessage -title "提速"     $'\n虚拟系统的画面可以更流畅\n\n当前使用的XServer较慢，切换成xlorie画面会更流畅\n\n切换步骤为：\n开始使用->显示设置->XServer管理->xlorie\n\n'  -center
	fi

	if [ "${XSRV_NAME}" == "xlorie" ] && [ ! -f /tmp/xlorie_workok.txt ]; then
		echo "Xvfb xlorie" > ${DirGuiConf}/xserver_order.txt

		# echo -e "\n\n您第一次使用xlorie\n\n如果桌面黑屏，请等待几秒钟\n如果画面正常，请点击确定\n\n" > "/exbin/tmp/promptmsg.txt"
		# echo2apk "#promptmsg"

		

		gxmessage -title "请确认"     $'\n您第一次使用xlorie，请确认画面显示是否正常\n\n'  -center -buttons "系统黑屏:1,画面正常:2"
		btnsel=$?
		case "$btnsel" in
			"2")
				# 画面正常
				touch /tmp/xlorie_workok.txt
				echo "xlorie" > ${DirGuiConf}/xserver_order.txt

				# 测试不稳，暂时不启用! 2025.03.02
				# create_quick_up_script
				;;
			*)
				;;
		esac
	fi
}

function checkif_xwindowmgr_started() {
	if [ -f /tmp/xwindowmgr_started ]; then
		echo "xwindowmgr 启动成功"  > ${APP_STDIO_NAME}
	else
		echo -e "\n\nxwindowmgr 启动失败\n当前xserver: ${XSRV_NAME}\n正在切换成Xvfb\n请重新打开虚拟电脑\n\n" | tee "/exbin/tmp/promptmsg.txt"  > ${APP_STDIO_NAME}
		echo2apk "#promptmsg"

		echo "Xvfb xlorie">${DirGuiConf}/xserver_order.txt
	fi
}

function vmSwitch2DesktopMode() {
	echo2apk '#vmSwitch2DesktopMode'
}

function start_xserver() {

	# test for xlorie
	# echo "192.168.1.13:2">/tmp/x_remote_server_addr

	if [ -f /tmp/x_remote_server_addr ]; then
		x11_redirect_to=`cat /tmp/x_remote_server_addr`
	fi

	if [ "$x11_redirect_to" != "" ]; then
		(sleep 3;echo killing...;pkill controllee) &
		DISPLAY=${x11_redirect_to} controllee -tryxserver
		if [ $? -ne 0]; then
			echo "远端xserver连接失败：${x11_redirect_to}"
			x11_redirect_to=
			rm -rf /tmp/x_remote_server_addr
		fi

	fi

	if [ "$x11_redirect_to" != "" ]; then

		echo "x11 redirecting..."
		pwd

		export DISPLAY=$x11_redirect_to

		# 已移到 vm_config.sh中
		# export PULSE_SERVER=tcp:127.0.0.1:4713

		if [ -f /tmp/xstarted ]; then
			exit 0
		fi

		touch /tmp/xstarted
		if [ "$action" == "normal_start" ]; then
			echo2apk 'LinuxStarted'
		fi

		# 既然已经开启X11重定向的功能，视为XServer已经在远端运行着了
		# 这里将不再启动XServer！
		echo -e "\nX11屏幕转发地址: |${x11_redirect_to}|"
		echo -e "若转发失败，请删除这个文件：/tmp/x_remote_server_addr"
		echo -e "\n\n\n"

	else
		displayid=
		pidof_xserver=
		xserver_listen_port=

		if [ -f ~/fb_control/controllee ]; then
			echo "found newer controllee at ~/fb_control/controllee"
			echo "copy to "`pwd`
			cp -f ~/fb_control/controllee ${app_home}/
			chmod 755 ${app_home}/controllee
		fi

		# 2025.03.01 未测试完成
		xlorie_quickup=2
		if [ -x ${app_home}/xlorie_quickup.sh ]; then
			source ${app_home}/xlorie_quickup.rc
			# . ${tools_dir}/vm_getuimode.rc
			controllee -tryxserver
			xlorie_quickup=$?
		fi

		# 启动xserver
		if [ $xlorie_quickup -ne 0 ]; then
					# 2024.04.10 确定：6002 在部分机型上启动不了的，还是得从6004开始
					for testport in {6004..6005}
					do
						echo "testing port ${testport}"
						controllee -trybind ${testport} 2>/dev/null
						if [ $? -eq 0 ]; then
							xserver_listen_port=${testport}
							displayid=$(($testport-6000))
							break;
						fi
					done
					if [ "${displayid}" == "" ] || [ "${xserver_listen_port}" == "" ]; then
						echo -e "图形进程启动失败! \n 6004..6005 端口都被占用"
						echo "$action"

						if [ "$action" == "normal_start" ]; then
							exit 2
						fi
					fi

					export XSRV_NAME=
					export DISPLAY=:${displayid}
					export MAX_FRAMEBUFFER_WIDTH=4096
					export MAX_FRAMEBUFFER_HEIGHT=4096
					export SECENDS_WAIT_XSERVER=`cat ${app_home}/app_boot_config/cfg_xserver_wait_seconds.txt 2>/dev/null`

					if [ "${SECENDS_WAIT_XSERVER}" == "" ]; then
					SECENDS_WAIT_XSERVER=1
					fi

					# 已移到 vm_config.sh中
					# export PULSE_SERVER=tcp:127.0.0.1:4713


					if [ -f /tmp/xstarted ]; then
						exit 0
					fi

					# touch /tmp/xstarted
					# cd ~

					. ${tools_dir}/vm_getuimode.rc

					export VM_DPI=`cat ${PATH_VMDPI}`
					# if [ -f ${PATH_VMDPI} ]; then
					# 	export VM_DPI=`cat ${PATH_VMDPI}`
					# fi
					# if [ "$VM_DPI" == "" ]; then
					# 	echo 150> ${PATH_VMDPI}
					# 	export VM_DPI=150
					# fi

					PATH_XSrvOrder=${DirGuiConf}/xserver_order.txt
					if [ -f ${PATH_XSrvOrder} ]; then
						XSrvOrder=`cat ${PATH_XSrvOrder}`
					fi
					# if [ -f ${PATH_XSrvOrder}.1 ]; then
					# 	XSrvOrder=`cat ${PATH_XSrvOrder}.1`
					# fi
					if [ "${XSrvOrder}" == "" ]; then
						# XSrvOrder="Xtigervnc Xvfb" # Xwayland

						# xlorie 不能排首位，好几个机型黑屏卡住
						XSrvOrder="Xvfb xlorie Xtigervnc" # Xwayland

						# XSrvOrder="xlorie Xvfb Xtigervnc" # Xwayland
					fi

					if [ "$DEBUG_XLORIE" != "0" ]; then
						XSrvOrder="xlorie"
					fi

					echo ""
					echo "starting XServer:"
					echo "===================================="
					echo "  DISPLAY: $DISPLAY"
					echo "XSrvOrder: $XSrvOrder"
					echo " language: ${LC_ALL}"
					echo "   uimode: ${uimode}"
					echo "  APP_DPI: ${APP_DPI}"
					echo "   VM_DPI: ${VM_DPI}"
					echo ""

					echo ""

					# xconfig

					MAX_RESOLUTION="${MAX_FRAMEBUFFER_WIDTH}x${MAX_FRAMEBUFFER_HEIGHT}"

					# java 版本的xserver: https://gitee.com/yelam2022/android-xserver
					# for i in `ls -A`; do echo "|$i|"; done
					for xsrv in ${XSrvOrder}
					do
						# echo "$xsrv"
						rm -rf /tmp/.X11-unix/*
						rm -rf /tmp/.X${displayid}-lock

						if [ "${xsrv}" == "xlorie" ]; then
							echo "正在启动xserver-xlorie"
							# ${RECOMMEND_SCREEN_WIDTH}x${RECOMMEND_SCREEN_HEIGHT}
							echo -e "xlorie 走 x11 协议，可在小于 ${MAX_RESOLUTION} 的范围内，动态调整为任意的分辨率"
							echo "#startlorie ${DISPLAY} ${VM_DPI}">$NOTIFY_PIPE

							sleep ${SECENDS_WAIT_XSERVER}
							# pidof_xserver=`pidof com.zzvm:serviceX11srv`
							# echo "${xsrv}进程ID: $pidof_xserver"
							# ps ax
						fi
						if [ "${xsrv}" == "Xvfb" ]; then
							which Xvfb || continue
							echo "正在启动xserver-xvfb"
							echo -e "xvfb 走 x11 协议，可在小于 ${MAX_RESOLUTION} 的范围内，动态调整任意的分辨率"
							export WST_SCREEN_SAVETO=/exbin/ipc/Xvfb_screen0

							# # 这几行指令会触发跟鸿蒙4.0一样的错误现象
							# mkdir -p /tmp/.X11-unix/X0 2>/dev/null
							# echo "ls -al /tmp/.X11-unix/"
							# ls -al /tmp/.X11-unix/

							# LD_LIBRARY_PATH=/gl4es-port/lib  # 可用于Xvfb，但貌似没加速作用
							Xvfb +extension XTEST +extension XFIXES +extension DAMAGE +extension RANDR +extension DOUBLE-BUFFER \
							-ac -listen tcp ${DISPLAY} -screen 0 ${MAX_FRAMEBUFFER_WIDTH}x${MAX_FRAMEBUFFER_HEIGHT}x24 -fbdir ${app_home}/ipc -dpi ${VM_DPI} &
							# +extension GLX \
							# nohup Xvfb +extension XTEST +extension XFIXES +extension DAMAGE +extension RANDR +extension DOUBLE-BUFFER \
							# -ac -listen tcp ${DISPLAY} -screen 0 ${MAX_FRAMEBUFFER_WIDTH}x${MAX_FRAMEBUFFER_HEIGHT}x24 -fbdir ${app_home}/ipc -dpi ${VM_DPI} &
							# -a -nocursor 

							# 分辨率比较大的时候，映射fb文件耗时久一点， 所以这里比其它两个xserver多等一秒钟
							sleep ${SECENDS_WAIT_XSERVER}
							# pidof_xserver=`pidof Xvfb`
							# # if [ ${action} == "normal_start" ]; then
							# # fi

							# if [ "$pidof_xserver" == "" ]; then
							# 	echo ""
							# 	echo ""
							# 	echo "鸿蒙4.0中不能创建 unix-socket 文件？"
							# 	Xvfb +extension XTEST +extension XFIXES +extension DAMAGE +extension RANDR +extension DOUBLE-BUFFER \
							# 	-ac -listen tcp -nolisten unix   ${DISPLAY} -screen 0 ${MAX_FRAMEBUFFER_WIDTH}x${MAX_FRAMEBUFFER_HEIGHT}x24 -fbdir ${app_home}/ipc -dpi ${VM_DPI} &

							# fi
						fi
						if [ "${xsrv}" == "Xtigervnc" ]; then
							which Xtigervnc || continue
							echo "正在启动xserver-tigervnc"
							echo -e "Xtigervnc 走 x11协议，可在小于 ${MAX_RESOLUTION} 的范围内，动态调整任意的分辨率，改完源码测试，发现Xtigervnc不能在本地显示光标。。。"
							export vncPort=590${displayid}
							export WST_SCREEN_SAVETO=/exbin/ipc/Xvfb_screen0
							Xtigervnc ${DISPLAY} +extension XTEST +extension XFIXES +extension DAMAGE +extension RANDR +extension DOUBLE-BUFFER -retro \
							-geometry ${MAX_FRAMEBUFFER_WIDTH}x${MAX_FRAMEBUFFER_HEIGHT} -depth 24 -dpi ${VM_DPI} +extension MIT-SHM \
							-rfbport ${vncPort} -PasswordFile /etc/webvnc/password.data -SecurityTypes VncAuth -auth /home/droidvm/.Xauthority &

							# 允许其它网络客户端连接到此xserver
							xhost +

							sleep ${SECENDS_WAIT_XSERVER}
						fi
						if [ "${xsrv}" == "Xwayland" ]; then
							which Xwayland || continue
							echo -e "【仅供内部测试用】\n weston 走 wayland 协议，不支持动态调整分辨率，实测单独使用wayland很好，但套接一个xserver，就出奇的慢"
							export XDG_RUNTIME_DIR=${HOME}
							export WST_SCREEN_SAVETO=/exbin/ipc/Xvfb_screen0
							unset WAYLAND_DISPLAY
							# weston -B headless-backend.so --xwayland --use-gl --width=${RECOMMEND_SCREEN_WIDTH} --height=${RECOMMEND_SCREEN_HEIGHT} & # --scale=5 &
							weston -B headless-backend.so --use-gl --width=${RECOMMEND_SCREEN_WIDTH} --height=${RECOMMEND_SCREEN_HEIGHT} >/dev/null 2>&1 & # --scale=5 &
							export WAYLAND_DISPLAY=wayland-1
							sleep 2

							echo "正在启动xserver-xwayland"
							Xwayland ${DISPLAY} +extension XTEST +extension XFIXES +extension DAMAGE -ac -dpi ${VM_DPI} &
							# pidof_xserver=`pidof Xwayland`
							sleep 1
						fi

						# controllee -trybind ${xserver_listen_port} 2>/dev/null	# 这条指令在高通 "SDM660 AIE" CPU 上会卡住！
						# controllee -tryxserver									# 这条指令也会在部分机型上卡住

						controllee -tryxserver
						if [ $? -ne 0 ]; then
							export XSRV_NAME=
							export vncPort=
							echo "${xsrv} 启动失败, fail to tryxserver"
							echo ""
							# if [ -f ${PATH_XSrvOrder}.1 ]; then
							# 	rm -rf ${PATH_XSrvOrder}.1
							# fi
						else
							export XSRV_NAME=${xsrv}
							break
						fi
					done


		fi # 2025.03.02

		if [ "${XSRV_NAME}" == "" ]; then
			echo2apk "桌面加载失败"
			echo -e "图形进程启动失败! \n你需要卸载掉虚拟电脑并重新安装！\n\n注意：\n 在虚拟系统安装过程中，请保持前台运行，不要切换应用"
			echo "$action"

			if [ "$action" == "normal_start" ]; then
				exit 2
			fi

		fi
		echo "===================================="
		echo "图形进程启动成功: ${XSRV_NAME}"
		echo "===================================="

		echo "${XSRV_NAME}" > /tmp/xstarted

		echo "starting controllee: ${action}"
		CONTROLLEE_OPTIONS=""
		ENABLE_WEB_CONTROL=""
		if [ -f /tmp/enable_webctrl ] && [ "${XSRV_NAME}" == "Xvfb" ]; then
		# if [ $SCRIPT_DEBUG -eq 1 ] && [ "${XSRV_NAME}" == "Xvfb" ]; then
		# if [ "${uimode}" == "pc" ] && [ "${XSRV_NAME}" == "Xvfb" ]; then
			ENABLE_WEB_CONTROL=" -enablews"
		fi
		CONTROLLEE_OPTIONS+="${ENABLE_WEB_CONTROL}"

		if [ $APP_RELEASE_INTERNAL -eq 1 ]; then
			:
			# CONTROLLEE_OPTIONS+=" -dumpctrlmsg"
		fi

		cat <<- EOF > ${tools_dir}/vm_rt_restart_controllee.sh
			#!/bin/bash
			# 这个文件是由 start.sh 生成的，请不要改动
			exec controllee ${CONTROLLEE_OPTIONS} -enablepc -block_size 100 -fbin /exbin/ipc/Xvfb_screen0 2>&1
		EOF
		chmod a+x ${tools_dir}/vm_rt_restart_controllee.sh

		controllee ${CONTROLLEE_OPTIONS} -enablepc -block_size 100 -fbin /exbin/ipc/Xvfb_screen0 2>&1 &
		(sleep 0.5; echo2apk 'XServerStarted' ) &
		

		if [ "$action" == "normal_start" ]; then
			echo2apk 'LinuxStarted'
		fi


	fi

}

function close_xserver() {
	rm -rf /tmp/xstarted

	echo '#vmSwitch2ConsoleMode'>${NOTIFY_PIPE}
	echo "#stoplorie">$NOTIFY_PIPE

	pkill -f com.zzvm:serviceX11srv
	pkill Xvfb
	pkill Xtigervnc
	pkill weston
	pkill controllee
}

# # 既是 service 就不应该跟 gui 有关，所以从1.37版开始，去掉了！
# function services_after_gui() {
# 	dir_scripts=/etc/autoruns/services_after_gui
#     if [ -d ${dir_scripts} ]; then
#         # ls -al ${dir_scripts}
#         echo "${dir_scripts} 加载中..."
#         for i in ${dir_scripts}/*.sh; do
#             if [ -r $i ]; then
#                 echo "$i"
#                 . $i
#             fi
#         done
#         unset i
#     fi
# }

function autoruns_before_gui() {
	dir_scripts=/etc/autoruns/autoruns_before_gui
    if [ -d ${dir_scripts} ]; then
        # ls -al ${dir_scripts}
        echo "${dir_scripts} 加载中..."
        for i in ${dir_scripts}/*.sh; do
            if [ -r $i ]; then
                echo "$i"
                . $i
            fi
        done
        unset i
    fi
}

function autoruns_after_gui() {
    # cmd patch
	dir_scripts=/etc/autoruns/autoruns_after_gui
    if [ -d ${dir_scripts} ]; then
        # ls -al ${dir_scripts}
        echo -e "\n正在启动：${dir_scripts}/*.sh"
        for i in ${dir_scripts}/*.sh; do
            if [ -r $i ]; then
                echo "$i"
                . $i
            fi
        done
        unset i
    fi

	dir_scripts=/etc/autoruns/autoruns_after_gui
    if [ -d ${dir_scripts} ]; then
        # ls -al ${dir_scripts}
        echo -e "\n正在启动：${dir_scripts}/*.desktop"
        for i in ${dir_scripts}/*.desktop; do
            if [ -r $i ]; then
                echo "$i"
                xopen $i
            fi
        done
        unset i
    fi

	echo ""
	echo "系统启动完成"
}

function setup_gtk2_theme_for_tiny_de() {
	# return

	echo "正在设置 系统主题 环境变量"

	mkdir -p ~/.config/gtk2 2>/dev/null
	echo ''								> ~/.config/gtk2/gtkrc
	echo 'include "gtk_icon.rc"'		>>~/.config/gtk2/gtkrc
	echo 'include "gtk_theme.rc"'		>>~/.config/gtk2/gtkrc
	echo 'include "gtk_font.rc"'		>>~/.config/gtk2/gtkrc
	echo ''								>>~/.config/gtk2/gtkrc

	# 默认的图标
	if [ ! -f ~/.config/gtk2/gtk_icon.rc ]; then
		echo 'gtk-icon-theme-name = "Adwaita"'				> ~/.config/gtk2/gtk_icon.rc
		# echo 'gtk-cursor-theme-size = 64'					> ~/.config/gtk2/gtk_icon.rc
		# echo 'gtk-icon-theme-name = "elementary-xfce"'	> ~/.config/gtk2/gtk_icon.rc
	fi

	# 默认的外观
	if [ ! -f ~/.config/gtk2/gtk_theme.rc ]; then
		echo 'gtk-theme-name = "Adwaita"'						> ~/.config/gtk2/gtk_theme.rc
	fi

	# 默认的字体
	if [ ! -f ~/.config/gtk2/gtk_font.rc ]; then
		echo 'gtk-font-name="Sans 12"'							> ~/.config/gtk2/gtk_font.rc
	fi

	export GTK2_RC_FILES=~/.config/gtk2/gtkrc
	export GTK_THEME=$(cat ~/.config/gtk2/gtk_theme.rc|grep "gtk-theme-name"|awk -F'='  '{print $2;}'|awk -F'"'  '{print $2;}')
}

function setup_vars() {
	export PATH=$PATH:/usr/games
}

function create_DE_selector() {
	tmp_dsk_file="${HOME}/Desktop/switch_desktop_env.desktop"
	if [ ! -f ${tmp_dsk_file} ]; then
		# rm -rf ${tmp_dsk_file}
		echo "[Desktop Entry]"				> ${tmp_dsk_file}
		echo "Encoding=UTF-8"				>>${tmp_dsk_file}
		echo "Version=0.9.4"				>>${tmp_dsk_file}
		echo "Type=Application"				>>${tmp_dsk_file}
		echo "Name=切换桌面"				>>${tmp_dsk_file}
		echo "Exec=/exbin/tools/vm_set_desktop_env.sh"			>>${tmp_dsk_file}
		echo "Icon=/exbin/tools/zzswmgr/appicons/ic_gde.png"	>>${tmp_dsk_file}
		echo ""													>>${tmp_dsk_file}

		cp -f ${tmp_dsk_file} /usr/share/applications/
	fi


	# 启动图标 +x 权限
	chmod a+x ~/Desktop/*.desktop 2>/dev/null
	chmod a+x /usr/share/applications/*.desktop 2>/dev/null
	chmod a+x ${tools_dir}/*.sh 2>/dev/null
	chmod a+x ${tools_dir}/zzswmgr/*.py 2>/dev/null
}

function link_templates_dir() {
	if [ -d ./模板 ]; then
		(cd ~ && ln -s 模板  Templates)
	fi
}

function start_xwindowmgr() {

	# # 启动过程中，图形界面还未完全加载时，如果用户旋转了屏幕，得杀的旧的检测进程
	# pkill -f vm_startex_delay_check_winmgr.sh
	# vm_startex_delay_check_winmgr.sh &
	# # rm -rf /tmp/xwindowmgr_started
	# # (sleep 8;checkif_xwindowmgr_started) &

	# # if [ "${force_copy_xconf_files}" == "" ] || [ ${force_copy_xconf_files} -eq 0 ]; then
	# # 	if [ -f ${APP_FILENAME_URLTOOLS} ]; then
	# # 		export force_copy_xconf_files=1
	# # 	else
	# # 		export force_copy_xconf_files=0
	# # 	fi
	# # fi


	source ${tools_dir}/vm_configx.sh
	source ${tools_dir}/vm_onXstarted.sh

	echo ""
	echo "${GraphicsDE}" > /etc/droidvm/cfg_de.txt

	setup_vars
	link_templates_dir

	ps -ax | grep svc_virgl | grep -v grep
	if [ $? -eq 0 ]; then
		# export GALLIUM_DRIVER=virpipe
		# export MESA_GL_VERSION_OVERRIDE=4.0
		echo ""
	fi

	# 2024.05.18 挪到这里
	echo "正在运行 xconfig"
	xconfig

	if [ -f ${app_home}/app_boot_config/opacity_enable ]; then
		echo "正在启动透明显示效果混合程序"
		compton &
	fi

	# tmp_dsk_file="${HOME}/Desktop/switch_desktop_env.desktop"
	# rm -rf ${tmp_dsk_file}
	create_DE_selector


	# 2025.04.22 处理xfce4主题不生效的问题！
	if [ "${GraphicsDE}" != "pcmanfm" ]; then
		# export GDK_SCALE=2 # 在手机和平板上效果不一样, 最好不要硬开 
		unset GTK2_RC_FILES
		unset GTK_THEME
	fi

	# 启动 窗口管理器 等桌面程序
	if [ "${GraphicsDE}" == "xfce4" ]; then
		echo "正在启动 xfce4"
		unset GALLIUM_DRIVER
		unset MESA_GL_VERSION_OVERRIDE

		# export XDG_CURRENT_DESKTOP=XFCE
		# export DESKTOP_SESSION=xfce

		# patch for mesa.freedreno kgsl mode
		XFCE_CONF_XML=~/.config/xfce4/xfconf/xfce-perchannel-xml/xfwm4.xml
		if [ -f "${XFCE_CONF_XML}" ]; then
			sed -i 's|property name="vblank_mode" type="string" value="auto"|property name="vblank_mode" type="string" value="off"|g'  ${XFCE_CONF_XML}
		fi

		# which xfce4-tinysession >/dev/null 2>&1
		# if [ $? -eq 0 ]; then
		# 	# xfce4-tinysession &  # 启动失败
		# 	cp -f /etc/xdg/xfce4/xfconf/xfce-perchannel-xml/xfce4-session.xml.tiny    /etc/xdg/xfce4/xfconf/xfce-perchannel-xml/xfce4-session.xml

		# 	# 主题
		# 	xfconf-query -c xsettings -p /Net/ThemeName -s ${GTK_THEME}
		# 	xfconf-query -c xfwm4     -p /general/theme -s ${GTK_THEME}

		# 	# 背景
		# 	xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitorscreen/workspace0/last-image  -s /usr/share/backgrounds/xfce/xfce-flower.svg

		# 	jwm &
		# 	xfce4-session &
		# else
			if [ "${vmDistribution}" == "archlinux" ]; then
				echo "archlinux中xfce4要下特殊的指令才能顺利启动"
				xfce4-session < ${APP_STDIO_NAME} > ${APP_STDIO_NAME} 2>&1 &

				# ndktelnetd -l /bin/bash -p 5556
				# echo "telnetd 已在 5556 端口启动"
			else
				startxfce4 &
				# dbus-launch --exit-with-session xfce4-session < ${APP_STDIO_NAME} > ${APP_STDIO_NAME} 2>&1 &
				# pkill dbus-daemon
				# dbus-launch startxfce4
				# # export DESKTOP_SESSION=xfce
				# # export XDG_CONFIG_DIRS=/etc/xdg
				# # export XDG_CURRENT_DESKTOP=XFCE
				# # export XDG_DATA_DIRS=/usr/local/share:/usr/share
				# # export XDG_MENU_PREFIX=xfce-
				# # export XDG_RUNTIME_DIR=/tmp/runtime-1000
				# # xfce4-session < ${APP_STDIO_NAME} > ${APP_STDIO_NAME} 2>&1 &
			fi

		# fi

	elif [ "${GraphicsDE}" == "lxde" ]; then
		echo "正在启动 kde-plasma"
		unset GALLIUM_DRIVER
		unset MESA_GL_VERSION_OVERRIDE

		dbus-launch --exit-with-session startlxde &
	elif [ "${GraphicsDE}" == "dde" ]; then
		echo "正在启动 kde-plasma"
		unset GALLIUM_DRIVER
		unset MESA_GL_VERSION_OVERRIDE

		dbus-launch --exit-with-session startdde &
	elif [ "${GraphicsDE}" == "kde" ]; then
		echo "正在启动 kde-plasma"
		unset GALLIUM_DRIVER
		unset MESA_GL_VERSION_OVERRIDE

		dbus-launch --exit-with-session startplasma-x11 &
	elif [ "${GraphicsDE}" == "enlightenment" ]; then
		echo "正在启动 enlightenment"
		unset GALLIUM_DRIVER
		unset MESA_GL_VERSION_OVERRIDE
		enlightenment_start &
	elif [ "${GraphicsDE}" == "gnome" ]; then
		echo "正在启动 gnome"
		unset GALLIUM_DRIVER
		unset MESA_GL_VERSION_OVERRIDE

		XDG_SESSION_TYPE=x11 XDG_CURRENT_DESKTOP='ubuntu:GNOME' dbus-launch --exit-with-session gnome-session &
		XDG_SESSION_TYPE=x11 XDG_CURRENT_DESKTOP='ubuntu:GNOME' gnome-shell -r &
	else
		echo "正在启动 jwm"
		# setup_gtk2_theme_for_tiny_de
		jwm &
		sleep 0.1
		echo "正在启动 pcmanfm"
		pcmanfm --desktop &

		tmp_dsk_file="${HOME}/Desktop/startjwm.desktop"
		rm -rf ${tmp_dsk_file}
	fi


	# dbus-launch --exit-with-session startxfce4
	# spacefm --desktop &
	# pcmanfm --set-wallpaper=#223366 &
	# jwm &
	# startxfce4 &
	# icewm-session &
	# lxsession -s LXDE &
	# GALLIUM_DRIVER=virpipe  MESA_GL_VERSION_OVERRIDE=4.0 wine explorer /desktop=shell,${RECOMMEND_SCREEN_WIDTH}x${RECOMMEND_SCREEN_HEIGHT} &

	sleep 0.1

	# # 放这里 jwm 在 xlorie 下鼠标指针不会显示大指针
	# echo "正在运行 xconfig"
	# xconfig

	if [ -f /tmp/xstarted ]; then export XSRV_NAME=`cat /tmp/xstarted 2>/dev/null`;	fi
	if [ "${XSRV_NAME}" == "Xvfb" ] || [ "${XSRV_NAME}" == "Xtigervnc" ]; then # || [ "${XSRV_NAME}" == "xlorie" ]; then
		echo "正在将画面铺满屏幕"
		resize_screen ${RECOMMEND_SCREEN_WIDTH} ${RECOMMEND_SCREEN_HEIGHT}
	fi

	touch /tmp/xwindowmgr_started

	rm_flag_files &

}

function close_xwindowmgr() {
	pkill pcmanfm
	pkill jwm

	pkill xfce4-session
	pkill xfdesktop
	pkill xfwm4
	pkill xfce4-panel
	pkill xfsettingsd
	pkill Thunar

	pkill -f enlightenment_start

	pkill -f gnome-session-binary
	pkill gnome-shell


	# pkill fcitx
	# pkill fcitx5
}

function notify_app() {
	echo "#x11restarted" > ${NOTIFY_PIPE}
}

function performe_normal_start() {
	# rm -rf /tmp/x_remote_server_addr

	autoruns_before_gui
	start_xserver
	run_once
	start_xwindowmgr
}

function performe_sresize() {
	close_xwindowmgr
	resize_screen ${RECOMMEND_SCREEN_WIDTH} ${RECOMMEND_SCREEN_HEIGHT}
	notify_app
	start_xwindowmgr
}

function performe_xserver() {
	close_xwindowmgr
	close_xserver
	init_uimode
	start_xserver
	vmSwitch2DesktopMode
	notify_app
	start_xwindowmgr
}

function performe_xwinman() {
	close_xwindowmgr
	start_xwindowmgr
}

function performe_input_method() {

	echo "正在启动输入法"

	# if [ $(command -v fcitx) ]; then
	# 	fcitx -D &
	# elif [ $(command -v fcitx5) ]; then
	# 	fcitx5 &
	# else
	# 	gxmessage -title "输入法启动失败" "输入法启动失败，请先在软件管家中安装输入法"  -center &
	# fi


	echo "正在启动输入法"
	logfile=/tmp/start_fcitx.log
	if [ $(command -v fcitx) ]; then
		fcitx_libdbus=/usr/lib/aarch64-linux-gnu/fcitx/fcitx-dbus.so
		if [ ! -f ${fcitx_libdbus}.mod ]; then
			cp -f ${fcitx_libdbus}  ${fcitx_libdbus}.mod
			cp -f ${fcitx_libdbus}  ${fcitx_libdbus}.ori
			sed -i "s|dbus-launch --binary-syntax|dbus-faunch --binary-syntax|g"  ${fcitx_libdbus}.mod
		fi

		if [ -f ${app_home}/app_boot_config/fcitx_patch_enable ]; then
			if [ 0 -eq 1 ]; then
				# 这样启用了也没办法使用
				dbus-daemon --syslog --nofork --print-pid=8  --print-address=9 --config-file /usr/share/fcitx/dbus/daemon.conf \
				8>/tmp/fcitx-dbus-pid.txt \
				9>/tmp/fcitx-dbus-addr.txt &
				chmod a+x ${tools_dir}/zzswmgr/ezapp/fcitx5_dict_import_tool/dbus-faunch
				cp -f     ${tools_dir}/zzswmgr/ezapp/fcitx5_dict_import_tool/dbus-faunch  ${tools_dir}/zzswmgr/ezapp/fcitx5_dict_import_tool/dbus-launch
				cp -f ${fcitx_libdbus}.ori  ${fcitx_libdbus}
				PATH=${tools_dir}/zzswmgr/ezapp/fcitx5_dict_import_tool:$PATH fcitx -D >> $logfile 2>&1 &
			else
				cp -f ${fcitx_libdbus}.mod  ${fcitx_libdbus}
				fcitx -D >> $logfile 2>&1 &
			fi
		else
			cp -f ${fcitx_libdbus}.ori  ${fcitx_libdbus}
			fcitx >> $logfile 2>&1 &
		fi
	elif [ $(command -v fcitx5) ]; then
		fcitx5 >> $logfile 2>&1 &
	else
		gxmessage -title "输入法启动失败" "输入法启动失败，请先在软件管家中安装输入法"  -center &
	fi
}

function performe_adb_server() {
	echo "正在启动 adb-server"
	exec 4>/tmp/adbreplay
	# echo "test">&4
	adb -L tcp:5037 fork-server server --reply-fd 4 &
}

function get_graphics_desktop_env() {
	GraphicsDE=`cat ${app_home}/app_boot_config/cfg_de.txt 2>/dev/null`

	if [ "$GraphicsDE" == "" ]; then
		GraphicsDE="pcmanfm"
	fi

	export GraphicsDE
}

function run_as_daemon() {

	init_uimode

	if [ -x ./custom_startx.sh ]; then
		echo "正在调用 启动X的自定义脚本"
		# ./custom_startx.sh  2>&1 >$APP_STDIO_NAME <$APP_STDIO_NAME &
		./custom_startx.sh  2>&1 &
		echo2apk 'LinuxStarted'
		exit 0
	fi

	get_graphics_desktop_env


	# 进程不退出！
	rm -rf    ${X_DAEMON_PIPE}
	mkfifo    ${X_DAEMON_PIPE}
	chmod 777 ${X_DAEMON_PIPE}
	(sleep 0.01; echo "TURNON_LCD">${X_DAEMON_PIPE}; ) &
	while true
	do
		# X_ACTION_REQ=`head -n 1 ${X_DAEMON_PIPE}`
		read X_ACTION_REQ < ${X_DAEMON_PIPE}
		rltXioRead=$?
		if [ $rltXioRead -ne 0 ]; then
			echo "  rltXioRead: $rltXioRead"
			echo "        错误: 无法从管道读取指令"
			sleep 0.1
			rm -rf    ${X_DAEMON_PIPE}
			mkfifo    ${X_DAEMON_PIPE}
			chmod 777 ${X_DAEMON_PIPE}
			continue
		fi

		echo "X_ACTION_REQ: $X_ACTION_REQ"
		echo "  rltXioRead: $rltXioRead"
		echo ""
		# source $0

		cd ~
		source /exbin/tools/vm_config.sh
		case "${X_ACTION_REQ}" in
			"TURNON_LCD")
				vmSwitch2DesktopMode
				;;
			"LCD_RES_CHANGED"*)
				neww=`echo "${X_ACTION_REQ}"|awk '{print $2}'`
				newh=`echo "${X_ACTION_REQ}"|awk '{print $3}'`

				oldw=${RECOMMEND_SCREEN_WIDTH}
				oldh=${RECOMMEND_SCREEN_HEIGHT}

				export RECOMMEND_SCREEN_WIDTH=$neww
				export RECOMMEND_SCREEN_HEIGHT=$newh
				echo "RECOMMEND_SCREEN_WIDTH : ${RECOMMEND_SCREEN_WIDTH}"
				echo "RECOMMEND_SCREEN_HEIGHT: ${RECOMMEND_SCREEN_HEIGHT}"

				if [ "${oldw}" == "" ] || [ "${oldh}" == "" ]; then
					# app端的surfaceview已创建完成，现在可以启动xserver了
					performe_normal_start
					(sleep 0.01; echo "autoruns_after_gui">${X_DAEMON_PIPE}; ) &
				elif [ "${oldw}" != "${neww}" ] || [ "${oldh}" != "${newh}" ]; then
					# 旋转了手机，surfaceview大小有变化了，对虚拟系统而言，即是分辨率有变化了
					(sleep 0.01; echo "sresize">${X_DAEMON_PIPE}; ) &
				fi
				if [ "${XSRV_NAME}" == "Xvfb" ] || [ "${XSRV_NAME}" == "Xtigervnc" ]; then
					echo "#vmstartRender">$NOTIFY_PIPE
				fi
				;;
			"LCD_OFF")
				if [ "${XSRV_NAME}" == "Xvfb" ] || [ "${XSRV_NAME}" == "Xtigervnc" ]; then
					echo "#vmstopRender">$NOTIFY_PIPE
				fi
				;;
			"sresize")
				performe_sresize
				;;
			"xserver")
				get_graphics_desktop_env
				performe_xserver
				;;
			"xwinman") 
				get_graphics_desktop_env
				performe_xwinman
				;;
			"vmScreenSizeReq"*) 
				reqw=`echo "${X_ACTION_REQ}"|awk '{print $2}'`
				reqh=`echo "${X_ACTION_REQ}"|awk '{print $3}'`
				echo "虚拟机内部主动要求将分辨率调整为：$reqw $reqh"
				echo "#vmScreenSizeReq $reqw $reqh" > ${NOTIFY_PIPE}
				resize_screen $reqw $reqh
				;;
			"autoruns_after_gui") 
				autoruns_after_gui
				;;
			"im") 
				performe_input_method
				;;
			"adbsrv")
				performe_adb_server
				;;
			"start-fcitx-dbus")
				dbus-daemon --syslog --nofork --print-pid=8  --print-address=9 --config-file /usr/share/fcitx/dbus/daemon.conf \
				8>/tmp/fcitx-dbus-pid.txt \
				9>/tmp/fcitx-dbus-addr.txt &
				;;
			*)
				;;
		esac
	done
}




echo ""
echo ""
echo "startx action: |${action}|"
echo ""
echo ""
cd ~
source /exbin/tools/vm_config.sh
ls -al ${X_DAEMON_PIPE}


case "${action}" in
	"sresize")
		echo "指令 |${action}| 待写入"
		echo "sresize">${X_DAEMON_PIPE}
		echo "指令 |${action}| 已传送"
		;;
	"xserver")
		echo "xserver">${X_DAEMON_PIPE}
		echo "指令 |${action}| 已传送"
		;;
	"xwinman") 
		echo "xwinman">${X_DAEMON_PIPE}
		echo "指令 |${action}| 已传送"
		;;
	"vmScreenSizeReq")
		reqw=$2
		reqh=$3
		echo "vmScreenSizeReq $reqw $reqh">${X_DAEMON_PIPE}
		echo "指令 |${action}| 已传送"
		;;
	*)
		run_as_daemon
		;;
esac
